package com.example.service.service.impl;

import com.example.service.entity.User;
import com.example.service.repository.UserRepository;
import com.example.service.service.UserService;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 用户服务实现类
 * 实现UserService接口定义的所有业务操作
 * 
 * @author example
 * @since 1.0.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private StringEncryptor jasyptStringEncryptor;

    private final UserRepository userRepository;

    /**
     * 构造函数注入UserRepository
     * 
     * @param userRepository 用户数据访问对象
     */
    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User createUser(User user) {
        // 检查用户名是否已存在
        if (isUsernameExists(user.getUsername())) {
            throw new IllegalArgumentException("用户名已存在: " + user.getUsername());
        }

        // 设置默认值
        user.setFailedAccessAttempts(0);
        if(user.getStatus() == null){
            user.setStatus(1);
        }
        if(user.getIsDeleted() == null){
            user.setIsDeleted(0);
        }
        user.setCreatedBy(1L);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        // 密码加密
        user.setPassword(jasyptStringEncryptor.encrypt(user.getPassword()));
        return userRepository.save(user);
    }

    @Override
    public Optional<User> findUserById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public Optional<User> findUserByUsername(String username) {
        return Optional.ofNullable(userRepository.findByUsername(username));
    }

    @Override
    public Optional<User> findUserByEmail(String email) {
        return Optional.ofNullable(userRepository.findByEmail(email));
    }

    @Override
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User updateUser(User user) {
        // 检查用户是否存在
        if (!userRepository.existsById(user.getId())) {
            throw new IllegalArgumentException("User not found with id: " + user.getId());
        }
        
        // 检查用户名是否被其他用户使用
        User existingUser = userRepository.findByUsername(user.getUsername());
        if (existingUser != null && !existingUser.getId().equals(user.getId())) {
            throw new IllegalArgumentException("Username already exists: " + user.getUsername());
        }
        
        // 检查邮箱是否被其他用户使用
        existingUser = userRepository.findByEmail(user.getEmail());
        if (existingUser != null && !existingUser.getId().equals(user.getId())) {
            throw new IllegalArgumentException("Email already exists: " + user.getEmail());
        }
        
        return userRepository.save(user);
    }

    @Override
    public boolean deleteUser(Long id) {
        if (userRepository.existsById(id)) {
            userRepository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean isUsernameExists(String username) {
        return userRepository.existsByUsername(username);
    }

    @Override
    public boolean isEmailExists(String email) {
        return userRepository.existsByEmail(email);
    }
} 